package biz.datalk.industrialland.common.util;

import biz.datalk.commons.utils.IdProvider;
import biz.datalk.industrialland.common.component.filter.MDCFilter;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.Map;
import java.util.Optional;

/**
 * @author tarofang@163.com
 * @date 2024-01-29
 */
@Slf4j
public class LogMdcUtil {
    public static void setMdcContext() {
        try {
            Map<String, String> previous = MDC.getCopyOfContextMap();
            Map<String, String> map = Optional.ofNullable(previous).orElse(Maps.newHashMap());
            map.put(MDCFilter.TRACE_ID, IdProvider.createUUIDId()); // 每次都生成新的 traceId
            MDC.setContextMap(map);
        } catch (Exception ex) {
            log.warn("ex:{}", ex.getMessage(), ex);
        }
    }
}
